import { Injectable } from '@nestjs/common';
import { QiniuService } from '@app/qiniu';
import { exec, spawn } from 'child_process';
import * as archiver from 'archiver';
import * as extract from 'extract-zip';
import { createWriteStream, createReadStream } from 'fs';
import { log } from 'util';

@Injectable()
export class FileService {
  constructor(private readonly qiniuService: QiniuService) {}

  // 获取app信息
  getAppInfo = async () => {
    let urlPath = this.qiniuService.getFileUrl('app-armeabi-v7a-release.apk');
    // let filePath = await this.qiniuService.downloadFile(urlPath);
    // await this.analyzeApp('filePath');
    return this.analyzeApp('filePath');
  };

  // 分析app
  analyzeApp = async (path: string) => {
    path = '/Users/zzn/Desktop/app-armeabi-v7a-release.apk';
    let tools = '/Users/zzn/Library/Android/sdk/build-tools/29.0.3/aapt';
    let upZipPath = '/Users/zzn/Desktop/android-unzip';

    let packageString = await this.getShellExec(
      `${tools} dump badging ${path}`,
    );

    let packageName = /package: name='(\S+)'/.exec(packageString).pop();
    let versionName = /versionName='(\S+)'/.exec(packageString).pop();
    let sdkVersion = /sdkVersion:'(\d+)'/.exec(packageString).pop();
    let appName = /application-label:'(\S+)'/.exec(packageString).pop();
    let icon = /icon='(\S+)'/.exec(packageString).pop();

    // 解压
    await extract(path, { dir: upZipPath });
    // 读取 app icon 文件
    let readStream = createReadStream(upZipPath + '/' + icon);
    let resHash = await this.qiniuService.uploadFile(icon, readStream);

    console.log(resHash);
    return { packageName, versionName, sdkVersion, appName, icon };
  };

  // 执行指令
  getShellExec(cmd: string): Promise<string> {
    return new Promise((resolve, reject) => {
      exec(cmd, (error, stdout, stderr) => {
        error ? reject(error) : resolve(stdout || stderr);
      });
    });
  }
}
